package com.servlet;

import com.bean.*;
import com.service.FavoriteService;
import com.service.HistoryService;
import com.service.ViedoService;
import com.service.impl.FavoriteServiceImpl;
import com.service.impl.HistoryServiceimpl;
import com.service.impl.ViedoServiceImpl;
import com.utils.WebUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;


@WebServlet("/ViedoServlet.do")
public class ViedoServlet extends BaseServlet {
    ViedoService viedoService = new ViedoServiceImpl();
    HistoryService historyService = new HistoryServiceimpl();
    FavoriteService favoriteService=new FavoriteServiceImpl();

    //通过名字模糊查询
    protected void fuzzyQuery(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text-html;charset=UTF-8");
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        String content = req.getParameter("content");
        Page<Viedo> page = viedoService.page(content, pageNo, pageSize);
//        for (Viedo viedo : page.getItems()) {
//            System.out.println(viedo);
//        }
        req.setAttribute("page", page);

//        req.getSession().setAttribute("page",page);
        req.getRequestDispatcher("/client/index.jsp").forward(req, resp);
    }

    /**
     * 分页处理
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 获取请求的参数 pageNo 和 pageSize
//        System.out.println("222");
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), Page.PAGE_SIZE);
        //2 调用GoodsService.page(pageNo，pageSize)：Page 对象
        Page<Viedo> page = viedoService.page(pageNo, pageSize);
        page.setUrl("/ViedoServlet.do?action=page");
        //3 保存Page 对象到Request 域中
        request.setAttribute("page", page);
        //4 请求转发到pages/manager/goods_manager.jsp 页面
        request.getRequestDispatcher("/client/index.jsp").forward(request, response);

    }


    /**
     * 保存视频路径到数据库
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void saveViedo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");

//        User user = (User) req.getSession().getAttribute("user");
        String vname = req.getParameter("video_name");//视频名称
        String vtype = req.getParameter("type");//类型
        String vdesc = req.getParameter("text");//视频描述
        String upload = req.getParameter("upload");//上传者
        String pic = req.getParameter("imgPath");//视频图片地址
        String viedoPath = req.getParameter("viedoPath"); //视频路劲
        Viedo viedo = new Viedo();
        viedo.setVname(vname);
        viedo.setVtype(vtype);
        viedo.setVdesc(vdesc);
        viedo.setUpLoader(upload);
        viedo.setPic(pic);
        viedo.setPath(viedoPath);

        int viedo1 = viedoService.addViedos(viedo);
        /* req.getRequestDispatcher("/PersonalCenter.jsp").forward(req,resp);*/
//        resp.getWriter().write(viedo1);
//        resp.sendRedirect(req.getContextPath() + "ViedoServlet.do?action=uploadImg");
//
//        resp.sendRedirect(req.getContextPath()+"ViedoServlet.do?action=uploadviedo");


/*

        Integer number = Integer.valueOf(req.getParameter("number"));
        String idDown = req.getParameter("idDown");
        String upLoader = req.getParameter("upLoader");//上传者
        String path = req.getParameter("path");//视频路径
*/

//        BigDecimal price;

//        String times = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
//        if (pri != null && !"".equals(pri)) {
//            price = new BigDecimal(pri);
//        } else {
//            price = new BigDecimal(0);
//        }


        //创建对应的video对象,并保存到数据库
//        Viedo video = new Viedo(null, vname, vtype, vdesc, pic, number, idDown, upLoader, null, null, null, null, null, path);
//        viedoService.addViedos(video);
//        Gson gson = new Gson();
//        Map<String, Object> map = new HashMap<>();
//        map.put("msg", videoCover);
//        String s = gson.toJson(map);
//        resp.getWriter().write(s);

    }


    //上传图片
    protected void uploadImg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
//1.先判断上传的数据是否为多段数据（只有是多段的数据 才是文件上传的）
        if (ServletFileUpload.isMultipartContent(request)) {
            //创建FileItemFactory工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //解析上传的数据 得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(request);
                //循环判断 每一个表单项 是普通类型 还是上传的文件
                for (FileItem fileItem :
                        list) {
                    if (fileItem.isFormField()) {
                        //普通表单项
                        System.out.println("表单项的name = " + fileItem.getFieldName());
                        System.out.println("表单项的value = " + fileItem.getString("UTF-8"));
                    } else {
                        //上传的文件
                        System.out.println("表单项的name = " + fileItem.getFieldName());
                        System.out.println("上传的文件名 = " + fileItem.getName());
                        //生成以毫秒值.jpg为文件名的图片
                        String pathPartName = System.currentTimeMillis() + ".jpg";
                        fileItem.write(new File("e:\\18jin\\" + pathPartName));
                        String path = "http://localhost:8082/img/" + pathPartName;
                        //将Ajax字符串传到前端
                        System.out.println(path);
                        response.getWriter().write(path);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    //上传视频
    protected void uploadviedo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
//1.先判断上传的数据是否为多段数据（只有是多段的数据 才是文件上传的）
        if (ServletFileUpload.isMultipartContent(request)) {
            //创建FileItemFactory工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //解析上传的数据 得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(request);
                //循环判断 每一个表单项 是普通类型 还是上传的文件
                for (FileItem fileItem :
                        list) {
                    if (fileItem.isFormField()) {
                        //普通表单项
                        System.out.println("表单项的name = " + fileItem.getFieldName());
                        System.out.println("表单项的value = " + fileItem.getString("UTF-8"));
                    } else {
                        //上传的文件
                        System.out.println("表单项的name = " + fileItem.getFieldName());
                        System.out.println("上传的文件名 = " + fileItem.getName());
                        //生成以毫秒值.MP4为文件名的视频
                        String pathPartName = System.currentTimeMillis() + ".mp4";
                        fileItem.write(new File("e:\\video\\" + pathPartName));
                        String path = "http://localhost:8082/video/" + pathPartName;//映射路径+名字
                        //将Ajax字符串传到前端
                        System.out.println(path);
                        response.getWriter().write(path);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 更改照片
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void changePhoto(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {

        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");
        // 获取文件的后缀
        //1.先判断上传的数据是否为多段数据（只有是多段的数据 才是文件上传的）
        if (ServletFileUpload.isMultipartContent(req)) {
            //创建FileItemFactory工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

            try {
                //解析上传的数据 得到每一个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(req);
                //循环判断 每一个表单项 是普通类型 还是上传的文件
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        //普通表单项
                        System.out.println("表单项的name = " + fileItem.getFieldName());
                        System.out.println("表单项的value = " + fileItem.getString("UTF-8"));
                    } else {
                        //上传的文件
//                        String fileName = System.currentTimeMillis() + suffix;
//                        fileItem.write(new File("D:\\videoAndImg\\" + fileName));
//                        String path = "http://localhost:80/videoAndImg/" + fileName;
//
//                        resp.getWriter().write(path);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


    //一键清除历史记录
    protected void delAllHistory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        historyService.delAll();
        req.getRequestDispatcher("/PersonalCenter.jsp").forward(req, resp);

    }
    //删除视频历史记录
    protected void delHistory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        historyService.deleteHIs(Integer.parseInt(id));
        req.getRequestDispatcher("/PersonalCenter.jsp").forward(req, resp);

    }

    /**
     * 添加历史记录
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */

    protected void findVideoById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id = Integer.parseInt(request.getParameter("id"));
        User user = (User) request.getSession().getAttribute("user");
        Viedo video = viedoService.findVideoById(id);
        History history = new History(null, user.getId(), video.getId(), new Date(), null);
        historyService.addHIs(history);
        List<HistoryList> historyLists = historyService.query(user.getId());

        request.setAttribute("viedo", video);
        request.getSession().setAttribute("historylist", historyLists);
        request.getRequestDispatcher("/single.jsp").forward(request, response);

    }

    //历史和收藏记录查询
    protected void queryHIs(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        //历史记录
        List<HistoryList> historyLists = historyService.query(user.getId());
        request.getSession().setAttribute("historylist", historyLists);
        //个人收藏
        List<FavoriteList> favoriteListList = favoriteService.queryFav(user.getId());
        request.getSession().setAttribute("favoriteListList", favoriteListList);
        response.sendRedirect("/PersonalCenter.jsp");
    }
}
